import { useState, useRef } from 'react';
import { toast } from 'sonner';

interface FileUploaderProps {
  onFileUpload: (file: File) => void;
}

export default function FileUploader({ onFileUpload }: FileUploaderProps) {
  const [isDragging, setIsDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };
  
  const handleDragLeave = () => {
    setIsDragging(false);
  };
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFiles(e.dataTransfer.files);
    }
  };
  
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleFiles(e.target.files);
      // 重置input以允许重复上传相同文件
      e.target.value = '';
    }
  };
  
  const handleFiles = (files: FileList) => {
    // 处理文件上传
    Array.from(files).forEach(file => {
      toast(`正在上传: ${file.name}`);
      // 模拟上传延迟
      setTimeout(() => {
        toast.success(`上传成功: ${file.name}`);
        onFileUpload(file);
      }, 1500);
    });
  };
  
  const triggerFileInput = () => {
    fileInputRef.current?.click();
  };
  
  return (
    <div 
      className={`border-2 border-dashed rounded-xl p-8 text-center transition-all duration-300 cursor-pointer ${
        isDragging 
          ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/10' 
          : 'border-gray-300 dark:border-gray-600 hover:border-blue-400 dark:hover:border-blue-500'
      }`}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
      onClick={triggerFileInput}
    >
      <input
        type="file"
        ref={fileInputRef}
        multiple
        className="hidden"
        onChange={handleFileInputChange}
      />
      
      <div className="flex flex-col items-center">
        <div className={`w-16 h-16 rounded-full flex items-center justify-center mb-4 ${
          isDragging ? 'bg-blue-100 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400' : 'bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400'
        }`}>
          <i className="fa-solid fa-cloud-upload-alt text-2xl"></i>
        </div>
        
        <h3 className="text-lg font-medium mb-1">拖放文件到此处或点击上传</h3>
        <p className="text-sm text-gray-500 dark:text-gray-400 mb-4 max-w-md">
          支持上传各种类型的文件，最大单个文件大小为10GB
        </p>
        
        <button 
          type="button"
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          onClick={triggerFileInput}
        >
          <i className="fa-solid fa-plus mr-2"></i>选择文件
        </button>
      </div>
    </div>
  );
}